package com.cnunicom.modules.tra.service.impl;

import com.cnunicom.modules.tra.entity.UnitEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cnunicom.common.utils.PageUtils;
import com.cnunicom.common.utils.Query;

import com.cnunicom.modules.tra.dao.ActivityDao;
import com.cnunicom.modules.tra.entity.ActivityEntity;
import com.cnunicom.modules.tra.service.ActivityService;


@Service("activityService")
public class ActivityServiceImpl extends ServiceImpl<ActivityDao, ActivityEntity> implements ActivityService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        ActivityEntity entity = getActivityEntity(params);
        String unitId = (String) params.get("unitId");
        IPage<ActivityEntity> page = this.page(
                new Query<ActivityEntity>().getPage(params,"create_time",false),
                new QueryWrapper<ActivityEntity>()
                .setEntity(entity)
                .like(StringUtils.isNotBlank(unitId),"unit_id",unitId)
        );
        return new PageUtils(page);
    }


    @Override
    public List<ActivityEntity> queryUnitsList(List<ActivityEntity> records, List<UnitEntity> units) {
        records.forEach(re -> {
            StringBuilder unitNames = new StringBuilder();
            String[] split = re.getUnitId().split(",");
            units.forEach(unit -> {
                for (String s : split) {
                    if (unit.getId().toString().equals(s)) {
                        unitNames.append(unit.getName()).append(",");
                    }
                }
            });
            re.setDef0(unitNames.toString());
        });
        return records;
    }

    private ActivityEntity getActivityEntity (Map<String, Object> params) {

        ActivityEntity entity = new ActivityEntity();

        String titile = (String)params.get("titile");
        String activation = (String) params.get("isActivation");

        if(StringUtils.isNotBlank(titile)){
            entity.setName(titile);
        }
        if (StringUtils.isNotBlank(activation)) {
            entity.setStatus(Integer.parseInt(activation));
        }

        return entity;
    }
}
